/******************************************************************************
 * @File name   :      UserAndRoleSetupController.java
 *
 * @Author      :      wujianxi
 *
 * @Date        :      2011-6-20
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-20 下午02:29:32        wujianxi     1.0            Initial Version
 * 2011-10-26 下午07:12:55        Wu Jianxi       1.1         refactor code
 * 2011-11-8 下午06:32:21         Wu Jianxi       1.2         增加导出功能
 * 2011-11-18 下午03:45:47        Wu Jianxi       1.3         增加品牌区分
 *****************************************************************************/
package com.cap.bts.framework.dm.userperm.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.cap.bts.framework.dm.userperm.service.IUserPermFuncService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.usermgnt.domain.Role;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserRole;
import com.cap.bts.framework.usermgnt.dto.AuthorizedUserQueryDto;
import com.cap.bts.framework.usermgnt.dto.AuthorizedUserResultDto;
import com.cap.bts.framework.usermgnt.dto.UserOrganizationGroupResultDto;
import com.cap.bts.framework.usermgnt.service.IEmployeeInfoService;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;


/**
 *
 */
@Controller
@RequestMapping(value = "/userPerm/userAndRole")
public class UserAndRoleSetupController extends BaseController{

    @Resource(name = "employeeInfoServiceImpl")
    private IEmployeeInfoService employeeInfoService;
    
    @Resource(name = "userPermFuncServiceImpl")
    private IUserPermFuncService userPermFuncService;
    
    @Resource(name = "userMgntServiceImpl")
    private IUserMgntService userMgntService;
    
    @Resource(name = "codeMappingImpl")
    private ICodeMapping codeMapping;
    
    private static final int SEARCH_FLAG = 1;
    /**
     * 根据userQueryDto分页查询审批通过的用户列表，并且需要按照用户ID升序。
     * 其中性别，就业状态来自值列表。限制整个查询条件的就业状态为2实习，4正式员工，5变更申请中
     * 
     * @Date : 2011-6-20
     * @param userQueryDto
     * @param model
     * @return
     * @throws AppException 
     */
    @RequestMapping(value = "/queryauthorizedusers")
    public String queryAuthorizedUsers(AuthorizedUserQueryDto userQueryDto, Model model)
        throws AppException {
        User user = getCurrentUser();
        userQueryDto.setBrandId(user.getBrandId());
        List<AuthorizedUserResultDto> listDto = new ArrayList<AuthorizedUserResultDto>(0);
        
        List<CodeInfo> genderList = new ArrayList<CodeInfo>();
        genderList = codeMapping.getCodeInfoByType("gender");
        userQueryDto.setEmploymentStatusId(4);
     //   Map<String,String> workStatusMap = CodeTextUtils.getStatusMap("Employee.WorkStatusExceptDraft");
//        workStatusMap.remove("1");
        
        listDto = employeeInfoService.queryAuthorizedUsersWithPaging(userQueryDto);
        
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, userQueryDto.getPager());
        model.addAttribute("listDto", listDto);
        model.addAttribute("genderList", genderList);
       // model.addAttribute("empStatusList", workStatusMap);
        model.addAttribute("queryDto", userQueryDto);
        
        return "dm/userPerm/userAndRole/query_authorized_users";
    }



    /**
     * 根据用户选择的userId来查询该用户相关的EmployeeInfo信息，关联的组织结构以及岗位信息。
     * 同时查询出该用户所有未被选择的角色列表，以及该用户关联的角色列表。
     * 该用户详细页面的角色列表中岗位默认角色，位于用户角色关联表中。通过查询岗位角色关联表来得出。
     * 
     * @Date : 2011-6-20
     * @param userId
     * @param model
     * @return
     * @throws AppException 
     */
    @RequestMapping(value = "/viewauthorizeduser/{userId}", method = RequestMethod.GET)
    public String viewAuthorizedUser(@PathVariable("userId") long userId, Model model)
        throws AppException {
        
        AuthorizedUserResultDto authDto = employeeInfoService.getEditedAuthorizedUser(userId);
        List<UserOrganizationGroupResultDto> orgUserList = employeeInfoService.getOrgGroupUserById(userId);
        List<Role> roleList = userMgntService.getRolesByUserCode(authDto.getUserCode());
        
        model.addAttribute("authDto", authDto);
        model.addAttribute("userOrgList", orgUserList);
        model.addAttribute("roleList", roleList);
        
        return "dm/userPerm/userAndRole/view_authorized_user";
    }
    /**
     * 设置人员和角色的修改页面
     * @Date        :      2011-12-8
     * @param userId
     * @param model
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/editauthorizeduser/{userId}", method = RequestMethod.GET)
    public String editAuthorizedUser(@PathVariable("userId") long userId, Model model)
        throws AppException {
        AuthorizedUserResultDto authDto = employeeInfoService.getEditedAuthorizedUser(userId);
        
        List<UserOrganizationGroupResultDto> orgUserList = employeeInfoService.getOrgGroupUserById(userId);
        
        String userCode = userMgntService.getUserByUserId(userId).getUserCode();
        
        // all role
        List<Role> allRoleList = userMgntService.getUndistributedRoleByUserId(userId);
        
        // this user's roles
        List<UserRole> selectedList = userMgntService.getSelectedRoleByCode(userCode);
        
        model.addAttribute("userId", userId);
        model.addAttribute("authDto", authDto);
        model.addAttribute("userOrgList", orgUserList);
        model.addAttribute("allRoleList", allRoleList);
        model.addAttribute("selectedList", selectedList);
        
        return "dm/userPerm/userAndRole/edit_authorized_user";
    }
    
    /**
     * 根据AuthorizedUserResultDto的userId和roleIds来更新用户
     * @Date        :      2011-6-20
     * @param userResultDto
     * @return
     * @throws AppException 
     */
    @RequestMapping(value = "/updateauthorizeduser")
    public String updateUserAndRoleRelation(Model model, HttpServletRequest request)
        throws AppException {
        long userId = Long.valueOf((String) request.getParameter("userId"));
        String[] roleArray = request.getParameterValues("check_two");
      /*  List<Long> roleList = new ArrayList<Long>();
        
        // delete tr_user_role
        userMgntService.deleteUserRolesByUserCode(userMgntService.getUserByUserId(userId).getUserCode());
        
        if (roleArray.length > 0) {
            for (int i = 0; i < roleArray.length; i++) {
                if (!"-1".equals(roleArray[i])) {
                    long roleId = Long.valueOf(roleArray[i]);
                    roleList.add(roleId);
                    userPermFuncService.updateUserAndRoleRelation(userId, roleId);
                }
            }
        }
        if (roleList != null && roleList.size() > 0) {
            userPermFuncService.jmsUserAndRole(userId, roleList);
        }*/
      //修改后方法
        this.userPermFuncService.updateUserAndRoleRelation(roleArray, userId);
        
        AuthorizedUserQueryDto userQueryDto = new AuthorizedUserQueryDto();
        userQueryDto.setOperationFlag(true);
        model.addAttribute("queryDto", userQueryDto);
        return "dm/userPerm/userAndRole/query_authorized_users";
    }
    
}
